package com.android.tea;

import java.util.ArrayList;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

import com.android.tea.api.ApiResult;
import com.android.tea.config.Config;
import com.android.tea.entity.Recommend;
import com.android.tea.net.HttpResult;
import com.android.tea.net.HttpResultJsonArray;
import com.android.tea.net.NetService;
import com.android.tea.util.Utils;

public class AlarmReceiver extends BroadcastReceiver {

	private static final String TAG = "AlamrReceiver";
	private Context mContext;
	@Override
	public void onReceive(Context context, Intent intent) {
		this.mContext = context;
		getNofication();
	}

	private void getNofication() {
		Log.e("Register", "register is running");
		new AsyncTask<Object, Integer, ApiResult<Object>>() {
			
			ArrayList<Recommend> info = null;
			@Override
			protected ApiResult<Object> doInBackground(Object... strs) {
				ApiResult<Object> apiResult = new ApiResult<Object>();
				apiResult.setResultCode(ApiResult.RESULT_FAIL);

				HttpResultJsonArray result = NetService.httpGetReturnJsonArray(mContext,
						Config.PUSH_URL, null);
				

				if (result.getResultCode() == HttpResult.RESULT_OK) {
					apiResult.setResultCode(ApiResult.RESULT_OK);
					Log.e("Json", "json is " + result.toString());
					try {
						info = parserJson(result.getJsonArray());
					} catch (JSONException e) {
						e.printStackTrace();
					}

				} else {
					apiResult.setFailCode(result.getFailCode());
					apiResult.setFailMessage(result.getFailMessage());
				}
				return apiResult;
			}

			@Override
			protected void onPostExecute(ApiResult<Object> apiResult) {
				if(info!=null&&info.size()>0) {
					Utils.showNotification(mContext,info, true);
				}
				
				super.onPostExecute(apiResult);
			}
		}.execute("");
	}
	private ArrayList<Recommend> parserJson(JSONArray jsonArray) throws JSONException {
		ArrayList<Recommend> list = null;
		if(jsonArray!=null) {
			list = new ArrayList<Recommend>();
			Recommend recommend = null;
			for(int i=0;i<jsonArray.length();i++) {
				JSONObject opt = (JSONObject) jsonArray.opt(i);
				recommend = new Recommend();
				recommend.setTitle(opt.getString("title"));
				recommend.setUrl(opt.getString("url"));
				recommend.setContent(opt.getString("content"));
				recommend.setType(opt.getString("type"));
				list.add(recommend);
			}
			Log.i("Json", "list "+list.size());
		}
		return list;
	}
}
